package com.axonactive.yolo.validation;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.axonactive.yolo.domain.UserEmail;
import com.axonactive.yolo.dto.SignupParameters;
import com.axonactive.yolo.service.interfaces.UserEmailService;
import com.axonactive.yolo.util.Utils;

@Component
public class SignupValidator implements Validator {
	@Autowired
	UserEmailService userEmailService;

	@Override
	public boolean supports(Class<?> clazz) {
		return SignupParameters.class.isAssignableFrom(clazz);
	}

	@Override
	public void validate(Object target, Errors errors) {
		SignupParameters signupParameters = (SignupParameters) target;

		ValidationUtils.rejectIfEmpty(errors, "userEmail", "email.notnull");
		ValidationUtils.rejectIfEmpty(errors, "password", "password.notnull");
		ValidationUtils.rejectIfEmpty(errors, "confirmPassword",
				"confirm.password.notnull");

		if (signupParameters.getUserEmail().length() > 100) {
			errors.rejectValue("userEmail", "email.outOfRange");
		}
		if (signupParameters.getPassword().length() > 50) {

			errors.rejectValue("password", "password.outOfRange");
		}

		List<UserEmail> emailList = userEmailService.findAll();
		for (UserEmail mail : emailList) {
			if (signupParameters.getUserEmail().equals(mail.getEmail())) {
				errors.rejectValue("userEmail", "email.exist");
				break;
			}
		}

		if (!"".equals(signupParameters.getUserEmail())
				&& !Utils.isValidEmail(signupParameters.getUserEmail())) {
			errors.rejectValue("userEmail", "email.invalid");
		}

		if (!"".equals(signupParameters.getPassword())
				&& !Utils.isValidPassword(signupParameters.getPassword())) {
			errors.rejectValue("password", "password.format");
		}

		if (Utils.isValidPassword(signupParameters.getPassword())
				&& !"".equals(signupParameters.getConfirmPassword())
				&& !signupParameters.getConfirmPassword().equals(
						signupParameters.getPassword())) {
			errors.rejectValue("confirmPassword", "confirm.password.notmatch");
		}

	}

}
